package com.atguigu.yygh.service.impl;

import com.alibaba.fastjson.JSONObject;

import com.atguigu.yygh.model.hosp.BookingRule;

import com.atguigu.yygh.model.hosp.Hospital;
import com.atguigu.yygh.model.hosp.Schedule;
import com.atguigu.yygh.repository.ScheduleRepository;
import com.atguigu.yygh.service.DepartmentService;
import com.atguigu.yygh.service.HospitalService;
import com.atguigu.yygh.service.ScheduleService;
import com.atguigu.yygh.vo.hosp.BookingScheduleRuleVo;
import com.atguigu.yygh.vo.hosp.ScheduleOrderVo;
import com.atguigu.yygh.vo.hosp.ScheduleQueryVo;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.joda.time.DateTime;
import org.joda.time.DateTimeConstants;
import org.joda.time.format.DateTimeFormat;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @description: TODO
 * @author: 化一帆
 * @date: 2022/11/28 17:53
 * @version: v1.0
 */
@Service
public class ScheduleServiceImpl implements ScheduleService {
    @Autowired
    private ScheduleRepository scheduleRepository;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private HospitalService hospitalService;

    @Autowired
    private DepartmentService departmentService;

    /**
     * @description: 上传排班的接口
     * @author 化一帆
     * @date 2022/11/28 18:01
     */
    @Override
    public void save(Map<String, Object> paramMap) {
        //1.将传递的结合转换成Department对象[先将map转换为字符串，再将字符串转换为对象]
        String paramMapString = JSONObject.toJSONString(paramMap);
        Schedule schedule = JSONObject.parseObject(paramMapString, Schedule.class);

        //2.根据医院编号和排班的编号进行查询
        Schedule scheduleExist = scheduleRepository.getScheduleByHoscodeAndHosScheduleId(schedule.getHoscode(), schedule.getHosScheduleId());

        //3.判断
        if (scheduleExist != null) {
            scheduleExist.setUpdateTime(new Date());
            scheduleExist.setIsDeleted(0);
            scheduleExist.setStatus(1);
            scheduleRepository.save(scheduleExist);
        }else{
            schedule.setUpdateTime(new Date());
            schedule.setUpdateTime(new Date());
            schedule.setIsDeleted(0);
            schedule.setStatus(1);
            scheduleRepository.save(schedule);
        }
    }


    /**
     * @description: 查询排班的接口
     * @author 化一帆
     * @date 2022/11/28 18:58
     * @return
     */
    @Override
    public Page<Schedule> findPageSchedule(int page, int limit, ScheduleQueryVo scheduleQueryVo) {

        //1.设置Pageable对象，设置当前页和每页记录数
        Pageable pageable = PageRequest.of(page - 1, limit);

        //2.将vo对象封装的查询条件赋值给Schedule对象
        Schedule schedule = new Schedule();
        BeanUtils.copyProperties(scheduleQueryVo, schedule);
        schedule.setIsDeleted(0);
        schedule.setStatus(1);

        //3.创建Example对象
        ExampleMatcher matcher = ExampleMatcher.matching()
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING)
                .withIgnoreCase(true);
        Example<Schedule> example=Example.of(schedule,matcher);

        //4,调用方法，实现分页
        Page<Schedule> all=scheduleRepository.findAll(example,pageable);

        return all;
    }


    /**
     * @description: 删除排班信息的接口
     * @author 化一帆
     * @date 2022/11/28 19:18
     */
    @Override
    public void removeSchedule(String hoscode, String hosScheduleId) {
        //1.根据医院编号和排班编号查询出相关的信息
        Schedule schedule = scheduleRepository.getScheduleByHoscodeAndHosScheduleId(hoscode, hosScheduleId);
        //2.健壮性判断：如果这个对象等于空，我们不需要进行删除，如果这个对象不为空，则根据科室ID进行删除
        if(schedule!=null){
            scheduleRepository.deleteById(schedule.getId());
        }
    }

    /**
     * @description:  根据医院的编号和科室编号查询排班规则
     * @author 化一帆
     * @date 2022/12/1 13:21
     */

    @Override
    public Map<String, Object> getRuleSchedule(Long page, Long limit, String hoscode, String depcode) {
        Map<String, Object> result = new HashMap<>();

        //1、根据hoscode和depcode查询排班
        Criteria criteria = Criteria.where("hoscode").is(hoscode).and("depcode").is(depcode);

        //2、根据工作日期workDate进行分组
        Aggregation agg = Aggregation.newAggregation(
                Aggregation.match(criteria),
                Aggregation
                        .group("workDate")
                        .first("workDate").as("workDate")
                        .count().as("docCount")
                        .sum("reservedNumber").as("reservedNumber")
                        .sum("availableNumber").as("availableNumber"),
                Aggregation.sort(Sort.Direction.ASC,"workDate"),
                Aggregation.skip((page-1)*limit),
                Aggregation.limit(limit)
        );

        //3、调用方法，最终执行
        AggregationResults<BookingScheduleRuleVo> aggResults =
                mongoTemplate.aggregate(agg, Schedule.class, BookingScheduleRuleVo.class);

        //4、分组结果
        List<BookingScheduleRuleVo> bookingScheduleRuleVoList = aggResults.getMappedResults();

        //5、分组查询的总记录数
        Aggregation totalAgg = Aggregation.newAggregation(
                Aggregation.match(criteria),
                Aggregation.group("workDate")
        );
        AggregationResults<BookingScheduleRuleVo> totalAggResults =
                mongoTemplate.aggregate(totalAgg,Schedule.class, BookingScheduleRuleVo.class);
        int total = totalAggResults.getMappedResults().size();

        //6、星期dayOfWeek
        for(BookingScheduleRuleVo bookingScheduleRuleVo : bookingScheduleRuleVoList) {
            Date workDate = bookingScheduleRuleVo.getWorkDate();
            String dayOfWeek = this.getDayOfWeek(new DateTime(workDate));
            bookingScheduleRuleVo.setDayOfWeek(dayOfWeek);
        }
        //---封装参数
        result.put("bookingScheduleRuleList",bookingScheduleRuleVoList);
        result.put("total",total);


        //7、根据hoscode获取hosname
        String hosname = hospitalService.getHospName(hoscode);

        //---封装参数
        Map<String, String> baseMap = new HashMap<>();
        baseMap.put("hosname",hosname);

        result.put("baseMap",baseMap);

        return result;
    }



    /**
     * @description:  根据日期获取周几的数据
     * @author 化一帆
     * @date 2022/12/1 14:49
     */
    private String getDayOfWeek(DateTime dateTime) {
        String dayOfWeek = "";
        switch (dateTime.getDayOfWeek()) {
            case DateTimeConstants.SUNDAY:
                dayOfWeek = "周日";
                break;
            case DateTimeConstants.MONDAY:
                dayOfWeek = "周一";
                break;
            case DateTimeConstants.TUESDAY:
                dayOfWeek = "周二";
                break;
            case DateTimeConstants.WEDNESDAY:
                dayOfWeek = "周三";
                break;
            case DateTimeConstants.THURSDAY:
                dayOfWeek = "周四";
                break;
            case DateTimeConstants.FRIDAY:
                dayOfWeek = "周五";
                break;
            case DateTimeConstants.SATURDAY:
                dayOfWeek = "周六";
                break;
            default:
                break;
        }
        return dayOfWeek;
    }

    /**
     * @description:  根据医院编号，科室信息和工作日期，查询排班详细信息
     * @author 化一帆
     * @date 2022/12/1 20:57
     */
    @Override
    public List<Schedule> getDetailSchedule(String hoscode, String depcode, String workDate) {
        //1、hoscode+depcode+workDate 查询排班列表
        List<Schedule> scheduleList =
                scheduleRepository.findByHoscodeAndDepcodeAndWorkDate(hoscode,depcode,new DateTime(workDate).toDate());
        //2、将所有的数据封装，schedule.param （医院名称、科室名称、日期对应星期）
        scheduleList.forEach(item->{this.packSchedule(item);});
        return scheduleList;
    }


    /**
     * @description:  封装排班详情其他值  医院名称，科室名称，日期对应日期
     * @author 化一帆
     * @date 2022/12/1 21:21
     */
    private Schedule packSchedule(Schedule schedule) {
        //医院名称
        schedule.getParam().put("hosname",hospitalService.getHospName(schedule.getHoscode()));
        //科室名称
        schedule.getParam().put("depname",departmentService.getDepName(schedule.getHoscode(),schedule.getDepcode()));
        //日期对应星期
        schedule.getParam().put("dayOfWeek",this.getDayOfWeek(new DateTime(schedule.getWorkDate())));

        return schedule;
    }


    /**
     * @description: 获取可预约的排班数据
     * @author 化一帆
     * 1.显示当前日期往后10天的数据
     * @date 2022/12/7 20:01
     */
    @Override
    public Map<String, Object> getBookingScheduleRule(Integer page, Integer limit, String hoscode, String depcode) {

        //1.获取预约的规则，
        //根据医院的编号，hosp对象中的rule属性
        Hospital hospital = hospitalService.getByHoscode(hoscode);
        BookingRule bookingRule = hospital.getBookingRule();

        //2.获取可预约的日期的数据（分页）【获取当前天数后面10天的数据或者5天的数据】
        IPage iPage = this.getListDate(page,limit,bookingRule);

        //通过ipage得到可预约日期的相关内容【日期集合】
        List<Date> dateList = iPage.getRecords();

        //3.给当天有排班的日期创建vo对象
        // 根据可预约的日期获取科室的相关的数量(医院编号，科室编号，可预约日期)
        // 【比如说日期中有哪些可预约数量，有哪些剩余数量，以及号源信息等等】
        //构造 mongodb中的查询条件


        //对改日期内的排班进行分组聚合
        Criteria criteria = Criteria.where("hoscode").is(hoscode).and("depcode").is(depcode).and("workDate").in(dateList);

        Aggregation agg = Aggregation.newAggregation(
                Aggregation.match(criteria), //匹配条件
                Aggregation.group("workDate").first("workDate").as("workDate")  //使用日期字段进行分组
                        .count().as("docCount")//排班数量
                        .sum("availableNumber").as("availableNumber")//剩余数
                        .sum("reservedNumber").as("reservedNumber")//可预约数
        );
        AggregationResults<BookingScheduleRuleVo> aggregateResult = mongoTemplate.aggregate(agg, Schedule.class, BookingScheduleRuleVo.class);
        List<BookingScheduleRuleVo> scheduleVoList = aggregateResult.getMappedResults();

        //4.合并数据【创建一个map集合，key日期workDate，value 代表BookingScheduleRuleVo】
        //5、list 转成 map
        Map<Date, BookingScheduleRuleVo> scheduleVoMap = new HashMap<>();

        scheduleVoMap = scheduleVoList.stream().collect(
                Collectors.toMap(BookingScheduleRuleVo::getWorkDate, BookingScheduleRuleVo -> BookingScheduleRuleVo)
        );

        //获取可预约的排班的规则
        //给当天没有排班的日期创建vo对象。只赋值当天的日期属性，以便在前端页面展示
        ArrayList<BookingScheduleRuleVo> bookingScheduleRuleVoList = new ArrayList<>();
        for (int i = 0; i <dateList.size() ; i++) {
           Date date= dateList.get(i);//拿到当前的日期
           //从map集合中根据key【日期】获取value【值】
            BookingScheduleRuleVo bookingScheduleRuleVo = scheduleVoMap.get(date);


            if(null == bookingScheduleRuleVo) { // 说明当天没有排班医生
                bookingScheduleRuleVo = new BookingScheduleRuleVo();
                bookingScheduleRuleVo.setWorkDate(date);
                bookingScheduleRuleVo.setDocCount(0);
                bookingScheduleRuleVo.setAvailableNumber(-1);//-1表示无号
                bookingScheduleRuleVo.setReservedNumber(-1);
            }

            bookingScheduleRuleVo.setWorkDateMd(date);
            bookingScheduleRuleVo.setDayOfWeek(this.getDayOfWeek(new DateTime(date)));

            //最后一页最后一条记录为即将预约。  0：正常, 1：即将放号，-1：当天已停止挂号
            //判断是否为最后一条数据
            if( page == iPage.getPages() && i == dateList.size()-1 ) {
                bookingScheduleRuleVo.setStatus(1);//即将放号
            } else {
                bookingScheduleRuleVo.setStatus(0);//正常
            }

            //当天（第一页第一条） 如果过了停挂时间 status=-1 ，当天已停止预约挂号
            if( page == 1 && i == 0 ) {
                DateTime stopTime = this.getDateTime(new Date(), bookingRule.getStopTime());
                if(stopTime.isBeforeNow()) {
                    bookingScheduleRuleVo.setStatus(-1);//当天停止挂号
                }
            }

            bookingScheduleRuleVoList.add(bookingScheduleRuleVo);
        }

        // -----------------封装返回结果--------------------------
        Map<String, Object> result = new HashMap<>();
        Map<String, String> baseMap = new HashMap<>();

        baseMap.put("hosname", hospitalService.getHospName(hoscode));
        baseMap.put("bigname", departmentService.getDepartment(hoscode, depcode).getBigname());
        baseMap.put("depname", departmentService.getDepartment(hoscode, depcode).getDepname());
        baseMap.put("workDateString", new DateTime().toString("yyyy年MM月"));
        baseMap.put("releaseTime", bookingRule.getReleaseTime());
        baseMap.put("stopTime", bookingRule.getStopTime());

        result.put("bookingScheduleList", bookingScheduleRuleVoList);
        result.put("total", iPage.getTotal());
        result.put("baseMap", baseMap);

        return result;
    }




    /**
     * @description:  获取可预约日期的分页的数据
     * @author 化一帆
     * @date 2022/12/7 21:57
     */
    private IPage getListDate(Integer page, Integer limit, BookingRule bookingRule) {
        //1.获取当天的放号的时间  年 月 日 小时 分钟
        DateTime releaseTime = this.getDateTime(new Date(), bookingRule.getReleaseTime());

        //2.获取预约的周期
        Integer cycle = bookingRule.getCycle();

        //3.判断是否在当天的预约的时间范围内
        //如果当天的放号的时间已经过去了，预约周期从后一天开始计算，周期+1
        if(releaseTime.isBeforeNow()){
            //如果已经超过当天的放号时间，周期+1
            cycle+=1;
        }

        //4.根据cycle获取可预约的所有的日期

        ArrayList<Date> dateList = new ArrayList<>();

        for (int i = 0; i <cycle ; i++) {//比如3月1号往后推迟10天，得到所有的日期，最终放到datelist集合中

            DateTime curDateTime = new DateTime().plusDays(i); //往后推一天
            String dateString = curDateTime.toString("yyyy-MM-dd");//创建日期  年 月  日
            dateList.add(new DateTime(dateString).toDate());
        }

        //5.因为预约的周期不同，每页最多显示7天的数据，超过7天的数据需要进行分页
        ArrayList<Date> pageDateList = new ArrayList<>();

        int start = (page-1)*limit;//开始位置
        int end = (page-1)*limit+limit;//结束位置


        if(end > dateList.size()) {
            //如果得到的所有日期的数据集合小于7，直接显示
            end = dateList.size();
        }

        for (int i = start; i < end; i++) {
            pageDateList.add(dateList.get(i));
        }
        //如果可以显示的数据大于7，进行分页
        //借用MP中的Page封装返回值
        IPage<Date> iPage = new com.baomidou.mybatisplus.extension.plugins.pagination.Page(page, limit, dateList.size());
        iPage.setRecords(pageDateList);//将当前页的数据的封装
        return iPage;
    }

    /**
     * @description:
     * @author 化一帆
     * @date 2022/12/8 19:16
     * 实体类中的时间属性为字符串类型，需要将字符串类型转换为时间类型，此方法一举两得
     * 将Date日期（yyyy-MM-dd HH:mm）转换为DateTime
     * 方便调用dateTime对象中内置的方法
     */
    private DateTime getDateTime(Date date, String timeString) {
        //注意：中间有个空格
        String dateTimeString = new DateTime(date).toString("yyyy-MM-dd") + " " + timeString;
        DateTime dateTime = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm").parseDateTime(dateTimeString);
        return dateTime;
    }


    /**
     * @description:  根据id获取排版的数据
     * @author 化一帆
     * @date 2022/12/8 16:42
     */
    @Override
    public Schedule getById(String id) {
        Schedule schedule = scheduleRepository.findById(id).get();
        return this.packSchedule(schedule);
    }


    /**
     * @description:  根据排班ID获取预约下单数据
     * @author 化一帆
     * @date 2022/12/8 19:02
     */
    @Override
    public ScheduleOrderVo getScheduleOrderVo(String scheduleId) {
        ScheduleOrderVo scheduleOrderVo = new ScheduleOrderVo();
        //1.根据排班的id获取排班对象
        Schedule schedule = scheduleRepository.findById(scheduleId).get();

        //2.查询预约规则
        Hospital hospital = hospitalService.getByHoscode(schedule.getHoscode());
        BookingRule bookingRule = hospital.getBookingRule();

        //3.向vo对象中赋值
        //3、赋值
        scheduleOrderVo.setHoscode(schedule.getHoscode());
        scheduleOrderVo.setDepcode(schedule.getDepcode());
        scheduleOrderVo.setHosScheduleId(schedule.getHosScheduleId());
        scheduleOrderVo.setAvailableNumber(schedule.getAvailableNumber());
        scheduleOrderVo.setTitle(schedule.getTitle());
        scheduleOrderVo.setReserveDate(schedule.getWorkDate());
        scheduleOrderVo.setReserveTime(schedule.getWorkTime());
        scheduleOrderVo.setAmount(schedule.getAmount());
        scheduleOrderVo.setHosname(hospitalService.getHospName(schedule.getHoscode()));

        //退号截止天数（如：就诊日期前一天为-1，当天为0）
        int quitDay = bookingRule.getQuitDay();
          //就诊日期的前一天
        DateTime quitTime=this.getDateTime(new DateTime(schedule.getWorkDate()).plusDays(quitDay).toDate(), bookingRule.getQuitTime());

        scheduleOrderVo.setQuitTime(quitTime.toDate());

        //预约开始时间
        DateTime startTime = this.getDateTime(new Date(), bookingRule.getReleaseTime());
        scheduleOrderVo.setStartTime(startTime.toDate());

        //预约截止时间
        DateTime endTime = this.getDateTime(new DateTime().plusDays(bookingRule.getCycle()).toDate(), bookingRule.getStopTime());
        scheduleOrderVo.setEndTime(endTime.toDate());

        //当天停止挂号时间
        DateTime stopTime = this.getDateTime(new Date(), bookingRule.getStopTime());
        scheduleOrderVo.setStopTime(stopTime.toDate());

        return scheduleOrderVo;
    }

    /**
     * @description:  消费rabbitmq中的数据，将数据更新到数据库【挂号之后更新可预约的数量】
     * @author 化一帆
     * @date 2022/12/9 17:12
     */
    @Override
    public void update(Schedule schedule) {
        schedule.setUpdateTime(new Date());
        scheduleRepository.save(schedule);
    }


}
